package fm.filter;

import com.alibaba.fastjson.JSON;
import fm.mongoService.UserService;
import fm.sys.token.MerchantToken;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名： fm.filter.PermisionFilter
 * 创建人： CM
 * 创建时间： 2016/3/6.
 */
public class PermisionFilter extends AuthorizationFilter {
    private static Logger LOGGER = LoggerFactory.getLogger(PermisionFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception {
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,OPTIONS");
        ((HttpServletResponse) response).setHeader("Access-Control-Max-Age", "3600");
        ((HttpServletResponse) response).setHeader("Content-Type", "application/json;charset=UTF-8");
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cache-Control, token");
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return true;
        } else {
//            LOGGER.info("request uri:{}, request headers:{}", ((HttpServletRequest) request).getRequestURI(), JSON.toJSONString(((HttpServletRequest) request).getHeaderNames()));
            String token = ((HttpServletRequest) request).getHeader("token");
            if (StringUtils.isNotEmpty(token)) {
                return tokenLogin(token);
            }


            if(isAjax((HttpServletRequest) request)){
                Map data= new HashMap();
                data.put("result", "-2");
                data.put("msg","身份验证已经失效，请重新登录!");

                response.getWriter().write(JSON.toJSONString(data));
                response.getWriter().flush();
                response.getWriter().close();
            }


            LOGGER.info("uri request has not permission:{}",((HttpServletRequest) request).getRequestURI());
            return false;
        }
    }


    private boolean tokenLogin(String token) throws Exception {
        MerchantToken ticket = new MerchantToken(token);
        Subject subject = SecurityUtils.getSubject();
        subject.login(ticket);
        return subject.isAuthenticated();
    }

    public boolean checkRoleWithResources() {
        return false;
    }


    boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }
}
